import axios from 'axios'
import {CODE, COOKIE_LIST, SERVER_URL} from '@/util/constant'
import Cookie from 'js-cookie'
import {get} from 'lodash'
import {router} from '../router'
import {Message} from 'element-ui'

function instance () {
  const request = axios.create({
    timeout: 5 * 1000,
    baseURL: SERVER_URL,
    headers: {[COOKIE_LIST.AUTHORIZATION]: Cookie.get(COOKIE_LIST.AUTHORIZATION)}
  })
  request.interceptors.request.use(function (config) {
    config.headers = {...config.headers, [COOKIE_LIST.AUTHORIZATION]: Cookie.get(COOKIE_LIST.AUTHORIZATION)}
    return config
  }, function (error) {
    return Promise.reject(error)
  })
  request.interceptors.response.use(function (response) {
    showResponseMessage(response)
  }, function (error) {
    // 403 重新登录
    // TODO 解决超时问题 跳转到静态页面
    console.log('超时', error)
    router.push('/login')
    Message({
      message: '请重新登录',
      type: 'error',
      showClose: true
    })
    return Promise.reject(error)
  })
  return request
}

const showResponseMessage = function (response) {
  let responseCode = get(response, 'data.code', CODE.FAIL)
  let responseMessage = get(response, 'data.msg', CODE.FAIL)
  if (CODE.SUCCESS === responseCode) {
    Message({
      message: responseMessage,
      type: 'success',
      duration: 2000
    })
    return response
  } else {
    Message({
      message: responseMessage,
      type: 'error',
      showClose: true
    })
  }
}

export const request = instance()
